const crypto = require('crypto')

// sign token  
function sign(data, key, expires_at, hash='sha256') {
  let hmac = crypto.createHmac(hash, key)
  let public_data = data.public_data.jion('$')
  let private_data = data.private_data.jion('$')
  let data = expires_at + '$'  + public_data + '$' + private_data
  hmac.update(data)
  let sign_str = hmac.digest('base64')
  return expires_at + '$' + public_data + '$' + sign_str
}

// validate token
function validate(key, private_data, token, hash='sha256') {
  let token_data = split_token(token)
  if (token_data.expires_at < new Date().getTime()) {
    return false
  }
  let data = {
    public_data: token_data.public_data,
    private_data: private_data,
  }
  return token === sign(data, key, expires_at, hash)
}

// split token, get expires_at and public_data
function split_token(token) {
  let token_arr = token.split('$')
  let expires_at = token_arr.shift()
  token_arr.pop()
  let public_data = token_arr
  return {
    expires_at,
    public_data
  }
}

// main
function main() {
  return {
    sign,
    validate,
    split_token
  }
}

module.exports = main()

